<template>
	<view class="container">
		<view class="form-title" @click="ceShi">添加地址</view>
		<!-- 姓名 -->
		<view class="form-item">
			<text class="label">姓名</text>
			<input class="input" type="text" placeholder="请输入姓名" :value="name" @input="handleNameInput"
				style="width: 92%;" />
		</view>

		<!-- 手机号 -->
		<view class="form-item">
			<text class="label">手机号</text>
			<input class="input" type="number" placeholder="请输入手机号" :value="phoneNumber" @input="handlePhoneInput"
				style="width: 92%;" />
		</view>

		<!-- 省市区选择 -->
		<view class="form-item">
			<text @click="ceShi" class="label">选择省市区</text>
			<picker mode="region" :value="region" :range="regionList" @change="bindRegionChange" @click="ceShi">
				<view id="xiaoPicker" class="picker" v-if="region[0] == 0">
					{{ regionList[0][region[0]] }} {{ regionList[1][region[1]] }} {{ regionList[2][region[2]] }}
				</view>
				<view id="xiaoPicker" class="picker" v-else>
					{{region[0]}} {{ region[1] }} {{ region[2] }}
				</view>
			</picker>
		</view>

		<!-- 详细地址 -->
		<view class="form-item">
			<text class="label">详细地址</text>
			<input class="input" type="text" placeholder="请输入街道/小区/楼号" :value="detailedAddress"
				@input="handleDetailedAddressInput" style="width: 92%;" />
		</view>

		<!-- 设为默认地址 -->
		<view class="form-item">
			<checkbox :checked="isDefault" @click="handleCheckboxChange">设为默认地址</checkbox>
		</view>

		<!-- 提交按钮 -->
		<view class="form-item">
			<button class="submit-btn" @click="submitForm">提交地址</button>
		</view>
	</view>
</template>

<script setup>
	import {
		ref
	} from 'vue';
	import {
		onLoad,
		onShow
	} from '@dcloudio/uni-app'
	import {
		addressApi
	} from '@/package/api/user_address.js';
	// 定义响应式数据
	const regionList = ref([
		['广东省', '北京市', '上海市'],
		['广州市', '深圳市', '珠海市'],
		['天河区', '海珠区', '越秀区'],
	]);
	// 定义响应式数据
	const region = ref([0, 0, 0]);
	const name = ref('');
	const phoneNumber = ref('');
	const detailedAddress = ref('');
	const isDefault = ref(false);

	// 处理姓名输入
	const handleNameInput = (event) => {
		name.value = event.target.value;
	};

	// 处理手机号输入
	const handlePhoneInput = (event) => {
		phoneNumber.value = event.target.value;
	};

	// 处理详细地址输入
	const handleDetailedAddressInput = (event) => {
		detailedAddress.value = event.target.value;
	};

	// 处理省市区选择变化
	const bindRegionChange = (event) => {
		const value = event.detail.value;
		region.value = value;
	};

	// 处理 checkbox 点击事件
	const handleCheckboxChange = (event) => {
		isDefault.value = !isDefault.value;
	};

	// 获取省市区名称
	const getRegionName = (indexes) => {
		const [p, c, d] = indexes;
		const provinces = uni.getSystemInfoSync().region.split(',');
		const cities = uni.getAddressInfoSync({
			provinceIndex: p
		}).cities;
		const districts = uni.getAddressInfoSync({
			cityIndex: c
		}).districts;
		return `${provinces[p]} ${cities[c]} ${districts[d]}`;
	};

	// 提交表单
	const submitForm = () => {
		// 验证姓名
		if (!name.value.trim()) {
			uni.showToast({
				title: '请输入姓名',
				icon: 'none',
			});
			return;
		}

		// 验证手机号
		const phoneRegex = /^1[3-9]\d{9}$/;
		if (!phoneNumber.value || !phoneRegex.test(phoneNumber.value)) {
			uni.showToast({
				title: '请输入有效的手机号',
				icon: 'none',
			});
			return;
		}

		// 验证详细地址
		if (!detailedAddress.value.trim()) {
			uni.showToast({
				title: '请输入详细地址',
				icon: 'none',
			});
			return;
		}

		// 从本地存储获取要编辑的地址信息
		const editAddressInfo = uni.getStorageSync('editAddressInfo');
		const addressId = editAddressInfo.id;

		// 构建修改后的地址信息
		const addressInfo = {
			id: addressId,
			name: name.value,
			phoneNumber: phoneNumber.value,
			province: region.value[0],
			city: region.value[1],
			district: region.value[2],
			detailedAddress: detailedAddress.value,
			isDefault: isDefault.value ? 1 : 0
		};

		// 将对象转换为 JSON 格式的字符串
		const addressInfoJson = JSON.stringify(addressInfo, null, 2);

		// 发送修改请求
		addressApi.edit(addressInfoJson).then((res) => {
			console.log('请求成功', res);
			uni.showToast({
				title: '地址修改成功',
				icon: 'success'
			});

			// 更新本地存储中的数据
			let storedAddressList = uni.getStorageSync('addressManagement');

			// 找到要修改的地址在本地存储中的索引
			const index = storedAddressList.findIndex(address => address.id === addressId);
			if (index !== -1) {
				// 判断是否将该地址设为默认地址
				if (isDefault.value) {
					// 如果设为默认地址，将其他地址的默认状态设为非默认
					storedAddressList.forEach(address => {
						address.isDefault = 0;
					});
				}
				// 更新本地存储中该地址的信息
				storedAddressList[index] = addressInfo;
				// 重新保存到本地存储
				uni.setStorageSync('addressManagement', storedAddressList);
			}

			// 清空表单数据
			name.value = '';
			phoneNumber.value = '';
			region.value = [0, 0, 0];
			detailedAddress.value = '';
			isDefault.value = false;

			// 清除本地存储中的编辑信息
			uni.removeStorageSync('editAddressInfo');
			// 返回上一页
			uni.navigateBack();
		}).catch((err) => {
			console.error('请求失败', err);
			uni.showToast({
				title: '地址保存失败',
				icon: 'none'
			});
		});
	};

	// 页面加载时弹出授权弹窗
	onLoad(() => {
		const editAddressInfo = uni.getStorageSync('editAddressInfo');
		console.log("123", editAddressInfo)
		console.log("123", regionList.value)
		regionList.value[0][0] = editAddressInfo.province;
		regionList.value[1][0] = editAddressInfo.city;
		regionList.value[2][0] = editAddressInfo.district;


		region.value[0] = editAddressInfo.province;
		region.value[1] = editAddressInfo.city;
		region.value[2] = editAddressInfo.district;




		console.log("123", regionList.value)
	});

	// 页面显示时回显数据
	onShow(() => {
		const editAddressInfo = uni.getStorageSync('editAddressInfo');
		if (editAddressInfo) {
			name.value = editAddressInfo.name;
			phoneNumber.value = editAddressInfo.phoneNumber;
			detailedAddress.value = editAddressInfo.detailedAddress;
			isDefault.value = editAddressInfo.isDefault === 1;

			// 找到省市区对应的索引
			// const provinceIndex = uni.getSystemInfoSync().region.split(',').indexOf(editAddressInfo.province);
			// const cities = uni.getAddressInfoSync({
			// 	provinceIndex
			// }).cities;
			// const cityIndex = cities.indexOf(editAddressInfo.city);
			// const districts = uni.getAddressInfoSync({
			// 	cityIndex
			// }).districts;
			// const districtIndex = districts.indexOf(editAddressInfo.district);

			// if (provinceIndex !== -1 && cityIndex !== -1 && districtIndex !== -1) {
			// 	region.value = [provinceIndex, cityIndex, districtIndex];
			// }
		}
	});
</script>
<style scoped>
	.container {
		padding: 20px;
		background-color: #f5f5f5;
		min-height: 100vh;
	}

	.form-title {
		font-size: 24px;
		font-weight: bold;
		color: #333;
		margin-bottom: 20px;
		text-align: center;
	}

	.form-item {
		margin-bottom: 20px;
	}

	.label {
		font-size: 16px;
		color: #666;
		display: block;
		margin-bottom: 5px;
	}

	.picker {
		padding: 12px;
		border: 1px solid #ddd;
		border-radius: 8px;
		background-color: #fff;
		box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
	}

	.input {
		width: 100%;
		padding: 12px;
		margin-top: 5px;
		border: 1px solid #ddd;
		border-radius: 8px;
		background-color: #fff;
		box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
		font-size: 16px;
	}

	.submit-btn {
		width: 100%;
		background-color: #007aff;
		color: #fff;
		border: none;
		border-radius: 8px;
		font-size: 18px;
		cursor: pointer;
		transition: background-color 0.3s ease;
	}

	.submit-btn:hover {
		background-color: #0056b3;
	}
</style>